package com.hzzftech.watchdog.busi.core.file.repository;

import com.hzzftech.watchdog.common.exception.file.FileException;
import com.hzzftech.watchdog.common.utils.StringUtils;

import java.io.File;
import java.util.List;
import java.util.Objects;

public class FileRepositoryManager {
    /**
     * 仓库根路径
     */
    private String repositoryRoot;

    /**
     * 仓库基础路径
     */
    private String repositoryBasePath;

    private String absolutePath;

    private File absolutePathFile;

    // 是否初始化了
    private boolean inited = false;

    private FileParser fileParse;


    /**
     * @param repositoryBasePath 文件资源库根路径
     */
    public FileRepositoryManager(String repositoryRoot, String repositoryBasePath, FileParser fileParse) {
        if (StringUtils.isEmpty(repositoryBasePath) || StringUtils.isEmpty(repositoryRoot) || Objects.isNull(fileParse)) {
            throw  new IllegalArgumentException("repositoryRoot或repositoryBasePath、fileParse为null!");
        }

        this.repositoryRoot = repositoryRoot;
        this.repositoryBasePath = repositoryBasePath;
        this.fileParse = fileParse;
        this.init();
    }

    public FileRepositoryManager init(){
        absolutePath = repositoryRoot + File.separator +repositoryBasePath;
        File f = new File(absolutePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        if (!f.canRead() || !f.canWrite()) {
            throw new FileException("文件“" + absolutePath + "”不可用，请检查！");
        }
        if (f.isFile()) {
            throw new FileException("资源库必须为一个目录");
        }

        absolutePathFile = new File(absolutePath);
        inited = true;

        return this;
    }


    public void parse() {
        if (!inited) throw new RuntimeException("文件仓库未初始化");
        fileParse.parse(absolutePathFile);
    }

    public List<?> getParseList() {
        return fileParse.getResultList();
    }


    public String getRepositoryRoot() {
        return repositoryRoot;
    }

    public void setRepositoryRoot(String repositoryRoot) {
        this.repositoryRoot = repositoryRoot;
    }

    public String getRepositoryBasePath() {
        return repositoryBasePath;
    }

    public void setRepositoryBasePath(String repositoryBasePath) {
        this.repositoryBasePath = repositoryBasePath;
    }

    public String getAbsolutePath() {
        return absolutePath;
    }

    public void setAbsolutePath(String absolutePath) {
        this.absolutePath = absolutePath;
    }

    public File getAbsolutePathFile() {
        return absolutePathFile;
    }

    public void setAbsolutePathFile(File absolutePathFile) {
        this.absolutePathFile = absolutePathFile;
    }

    public boolean isInited() {
        return inited;
    }

    public void setInited(boolean inited) {
        this.inited = inited;
    }

    public FileParser getFileParse() {
        return fileParse;
    }

    public void setFileParse(FileParser fileParse) {
        this.fileParse = fileParse;
    }
}
